import React from 'react';

export class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      msg: '',
    };
  }

  // 父组件定义接收子组件B数据的方法
  sendMsg = (msg) => {
    console.log('子组件B要传递给A的消息', msg);
    this.setState({
      msg: msg,
    });
  };

  render() {
    return (
      <div style={{ border: '1px solid red', padding: 24 }}>
        <h1>父组件：{this.state.msg}</h1>
        <ChildA msg={this.state.msg} />
        <ChildB sendMsg={this.sendMsg} />
      </div>
    );
  }
}

class ChildB extends React.Component {
  render() {
    return (
      <div style={{ border: '1px solid blue', padding: 24 }}>
        ChildB
        <button onClick={() => this.props.sendMsg('A你好')}>给B发消息</button>
      </div>
    );
  }
}

class ChildA extends React.Component {
  render() {
    return (
      <div style={{ border: '1px solid pink', padding: 24 }}>
        ChildA 我接收到的消息: {this.props.msg}
      </div>
    );
  }
}
